﻿using Microsoft.AspNetCore.Mvc;

using System.Text.Json;

namespace GitHubCopilotProxies.Handlers;

public class Telemetry
{
    public class TelemetryResponse
    {
        public int ItemsReceived { get; set; }
        public int ItemsAccepted { get; set; }
        public string? AppId { get; set; }
        public List<string> Errors { get; set; } = new List<string>();
    }
    public static async Task<TelemetryResponse> PostTelemetryAsync(HttpContext httpContext, [FromServices] ILogger<Telemetry> logger)
    {
        var response = new TelemetryResponse();
        if (httpContext is not { Request.ContentLength: > 0 }) return response;
        switch (httpContext.Request.ContentType)
        {
            case "application/x-json-stream":
                using (var reader = new StreamReader(httpContext.Request.Body))
                {
                    string? line;
                    while ((line = await reader.ReadLineAsync(httpContext.RequestAborted)) != null)
                    {
                        if (string.IsNullOrWhiteSpace(line)) continue;
                        response.ItemsReceived++;
                        try
                        {
                            //logger.LogInformation("TelemetryString: {line}", line);
                            // 处理遥测数据
                            response.ItemsAccepted++;
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "解析遥测数据时发生错误");
                            response.Errors.Add(ex.Message);
                        }
                    }
                }
                break;
            case "application/json":
                {
                    try
                    {
                        var jsonDocument = await JsonSerializer.DeserializeAsync<JsonElement>(httpContext.Request.Body, AppJsonSerializerContext.Default.JsonElement, httpContext.RequestAborted);
                        if (jsonDocument is { ValueKind: JsonValueKind.Array })
                            response.ItemsAccepted = response.ItemsReceived = jsonDocument.GetArrayLength();
                        else if (jsonDocument is { ValueKind: JsonValueKind.Object })
                            response.ItemsAccepted = response.ItemsReceived = 1;
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "解析遥测数据时发生错误");
                        response.Errors.Add(ex.Message);
                    }
                }
                break;
        }
        return response;
    }

}
